using MultiAgentsShared;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;

namespace MultiAgentsClient.Presentation.Component;

public sealed partial class AgentMainPanel : UserControl
{
    private readonly IEventBus eventBus;

    private int draggedIndex;

    public record DropMesageCommand(int FromId, int ToId);

    public AgentMainPanel()
    {
        InitializeComponent();
        DataContext = new BindableAgentMainPanelModel();

        eventBus = EventBus.Instance;
    }

    private void ListView_DragOver(object sender, DragEventArgs e)
    {
        e.AcceptedOperation = DataPackageOperation.Move;
    }

    private void ListView_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
    {
        var listView = sender as ListView ?? throw Debug.ShouldNotHappen();
        var draggedItem = e.Items[0];

        draggedIndex = listView.Items.IndexOf(draggedItem);
    }

    private void ListView_Drop(object sender, DragEventArgs e)
    {
        var listView = sender as ListView ?? throw Debug.ShouldNotHappen();

        var point = e.GetPosition(listView);

        var targetIndex = -1;
        for (int i = 0; i < listView.Items.Count; i++)
        {
            var container = listView.ContainerFromIndex(i) as ListViewItem;
            if (container != null)
            {
                var itemPosition = container.TransformToVisual(listView).TransformPoint(new Point(0, 0));

                if (point.Y < itemPosition.Y + container.ActualHeight)
                {
                    targetIndex = i;
                    break;
                }
            }
        }

        if (targetIndex == -1)
        {
            return;
        }

        eventBus.Publish(new DropMesageCommand(draggedIndex, targetIndex));
    }
}
